﻿
using System;
using System.Collections.Generic;
namespace SanguoSharp.Server
{
    /// <summary>
    /// 顺序响应处理
    /// </summary>
    public class QueueResponseHandler : ResponseHandler
    {
        private Queue<ResponseHandler> queue;

        protected QueueResponseHandler(Player requested, Player causedBy)
            : base(requested, causedBy)
        {
            queue = new Queue<ResponseHandler>();
        }
        protected QueueResponseHandler(Player requested)
            : this(requested, null)
        {
        }
        protected QueueResponseHandler() :
            this(null, null)
        {
        }
        protected QueueResponseHandler(Player requested, Player causedBy, int capacity)
            : base(requested, causedBy)
        {
            queue = new Queue<ResponseHandler>(capacity);
        }
        protected QueueResponseHandler(Player requested, int capacity)
            : this(requested, null, capacity)
        {
        }
        protected QueueResponseHandler(int capacity)
            : this(null, null, capacity)
        {
        }
        public QueueResponseHandler(List<ResponseHandler> handlers)
            : base()
        {
            queue = new Queue<ResponseHandler>(handlers.Count);
            foreach (ResponseHandler h in handlers)
                queue.Enqueue(h);
        }

        protected void AddHandler(ResponseHandler handler)
        {
            queue.Enqueue(handler);
        }

        protected override void OnStart()
        {
            try
            {
                PushHandler(queue.Dequeue());
            }
            catch (InvalidOperationException)
            {
                End();
            }
        }
        protected override void OnNext()
        {
            try
            {
                PushHandler(queue.Dequeue());
            }
            catch (InvalidOperationException)
            {
                End();
            }
        }
    }
}

